﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Charming.Showcase.Resources;
using InTheHand.UI.Popups;
using InTheHand.ApplicationModel;
using InTheHand.Storage;
using Windows.Storage;
using Windows.ApplicationModel.Store;

namespace Charming.Showcase
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //MessageBox.Show(Windows.ApplicationModel.Package.Current.Id.Version.ToString(true));
            string ver = typeof(System.Windows.Application).Assembly.GetName().Version.ToString();

            System.Windows.Resources.StreamResourceInfo sri = Application.GetResourceStream(InTheHand.ApplicationModel.Package.Current.Logo);

            System.Windows.Media.Imaging.BitmapImage img = new System.Windows.Media.Imaging.BitmapImage();
            img.SetSource(sri.Stream);

            System.Windows.Media.Imaging.WriteableBitmap wb = new System.Windows.Media.Imaging.WriteableBitmap(img);
            int rgb = wb.Pixels[0];
            
            byte r, g, b;
            r = (byte)((rgb & 0xFF0000) >> 16);
            g = (byte)((rgb & 0xFF00) >> 8);
            b = (byte)(rgb & 0xFF);
            System.Windows.Media.Color c = System.Windows.Media.Color.FromArgb(0xff, r, g, b);
            Application.Current.Resources.Add("AppAccentBrush", new System.Windows.Media.SolidColorBrush(c));

            //this.LayoutRoot.Background = (System.Windows.Media.SolidColorBrush)Application.Current.Resources["AppAccentBrush"];

            //System.Net.HttpWebRequest request = WebRequest.CreateHttp("http://bing.com");
            ///request.BeginGetResponse(callback, request);

            InTheHand.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted += MainPage_QuerySubmitted;
            //InTheHand.ApplicationModel.Search.SearchPane.GetForCurrentView().SuggestionsRequested += MainPage_SuggestionsRequested;
            InTheHand.UI.ApplicationSettings.SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        /*void MainPage_SuggestionsRequested(InTheHand.ApplicationModel.Search.SearchPane sender, InTheHand.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs args)
        {
            for(int i = 0; i < 3; i++)
            {
                args.Request.SearchSuggestionCollection.AppendResultSuggestion(i.ToString(), null, null, null, null);
            }
        }*/

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            InTheHand.ApplicationModel.Package p = InTheHand.ApplicationModel.Package.Current;

            //string resource = InTheHand.ApplicationModel.Resources.ResourceLoader.GetForCurrentView().GetString("ApplicationTitle");


            /*System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().CreateFile("cheese").Close();

            System.Diagnostics.Debug.WriteLine(System.Environment.TickCount);
            Windows.Storage.IStorageItem item = await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync("cheese");
            System.Diagnostics.Debug.WriteLine(System.Environment.TickCount);
           
            Windows.Storage.IStorageItem item2 = await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync("cheese2");
            System.Diagnostics.Debug.WriteLine(System.Environment.TickCount);*/
           
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().DataRequested += MainPage_DataRequested;
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().TargetApplicationChosen += MainPage_TargetApplicationChosen;
            base.OnNavigatedTo(e);
        }

        void MainPage_TargetApplicationChosen(InTheHand.ApplicationModel.DataTransfer.DataTransferManager sender, InTheHand.ApplicationModel.DataTransfer.TargetApplicationChosenEventArgs args)
        {
            providerName = args.ApplicationName;
        }

        void pct_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
        {
            System.Windows.MessageBox.Show(e.OriginalFileName);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView().DataRequested -= MainPage_DataRequested;
            base.OnNavigatingFrom(e);
        }

        void callback(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            request.EndGetResponse(result);
        }

        void MainPage_CommandsRequested(InTheHand.UI.ApplicationSettings.SettingsPane sender, InTheHand.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
        {
            args.Request.ApplicationCommands.Add(new InTheHand.UI.ApplicationSettings.SettingsCommand(1, "About", (c) => 
            { 
                InTheHand.UI.ApplicationSettings.AboutScreen.ShowAbout(c); 
            }));
        }

        void ShowAbout(IUICommand command)
        {
            MessageBox.Show(string.Format("Version {0}\r\nBy {1}\r\nPublisher {2}", InTheHand.ApplicationModel.Package.Current.Id.Version.ToString(true), InTheHand.ApplicationModel.Package.Current.Id.Author, InTheHand.ApplicationModel.Package.Current.Id.Publisher), InTheHand.ApplicationModel.Package.Current.DisplayName.ToUpper(), MessageBoxButton.OK);
        }

        bool flipflop;

        async void MainPage_DataRequested(InTheHand.ApplicationModel.DataTransfer.DataTransferManager sender, InTheHand.ApplicationModel.DataTransfer.DataRequestedEventArgs args)
        {
            InTheHand.ApplicationModel.DataTransfer.DataPackage dp = args.Request.Data;
            dp.Properties.Title = "Charming.Showcase";
            dp.Properties.Description = "An example share implementation";
            if (flipflop)
            {
                
                Microsoft.Xna.Framework.Media.MediaLibrary ml = new Microsoft.Xna.Framework.Media.MediaLibrary();
                dp.SetBitmap(ml.SavedPictures[0]); //Application.GetResourceStream(new Uri("Assets/ApplicationIcon.png", UriKind.Relative)).Stream);
            }
            dp.SetDataProvider(InTheHand.ApplicationModel.DataTransfer.StandardDataFormats.Text, TextProviderHandler);
            //dp.SetText("Something simple");
            dp.SetUri(new Uri("http://inthehand.com"));
            flipflop = !flipflop;
        }

        private string providerName;

        void TextProviderHandler(InTheHand.ApplicationModel.DataTransfer.DataProviderRequest request)
        {
            request.SetData(string.Format("the provider was {0}", providerName));
        }

        void MainPage_QuerySubmitted(InTheHand.ApplicationModel.Search.SearchPane sender, InTheHand.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs args)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("searched for {0}", args.QueryText));
            NavigationService.Navigate(new Uri("/SearchResults.xaml?queryText=" + args.QueryText, UriKind.Relative));
        }

        private async void PopupButton_Click(object sender, RoutedEventArgs e)
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp("https://api.twitter.com/oauth/request_token");
            request.Method = "POST";
            request.Headers["Authorization"] = string.Format("OAuth oauth_nonce=\"K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw\", oauth_callback=\"http%3A%2F%2Finthehand.com\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"{0}\", oauth_consumer_key=\"OqEqJeafRSF11jBMStrZz\", oauth_signature=\"Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D\", oauth_version=\"1.0\"", DateTime.UtcNow.Ticks); 
            request.BeginGetResponse(GotResponse, request);

            //InTheHand.Security.Authentication.Web.WebAuthenticationResult result = await InTheHand.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(InTheHand.Security.Authentication.Web.WebAuthenticationOptions.None, new Uri("https://api.twitter.com/oauth/access_token?oauth_consumer_key=FXP92icP5lVXzj24helAApyej"), new Uri("http://inthehand.com"));
            /*InTheHand.UI.Popups.MessageDialog md = new InTheHand.UI.Popups.MessageDialog("What colour would you like?", "CHARMING POPUPS");
            md.Commands.Add(new InTheHand.UI.Popups.UICommand("Red", RedInvoked));
            md.Commands.Add(new InTheHand.UI.Popups.UICommand("Green", GreenInvoked));
            md.ShowAsync();*/
        }

        private async void GotResponse(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
            InTheHand.Security.Authentication.Web.WebAuthenticationResult wabresult = await InTheHand.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(InTheHand.Security.Authentication.Web.WebAuthenticationOptions.None, new Uri("https://api.twitter.com/oauth/access_token?oauth_consumer_key=FXP92icP5lVXzj24helAApyej"), new Uri("http://inthehand.com"));
            
        }
        private void SharePushButton_Click(object sender, RoutedEventArgs e)
        {
            InTheHand.Phone.Tasks.ShareNfcLinkTask snlt = new InTheHand.Phone.Tasks.ShareNfcLinkTask();
            snlt.LinkUri = new Uri("http://peterfoot.net");
            snlt.Show();
        }

        void RedInvoked(IUICommand command)
        {
            Dispatcher.BeginInvoke(() => { this.LayoutRoot.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red); });
        }

        void GreenInvoked(IUICommand command)
        {
            Dispatcher.BeginInvoke(() => { this.LayoutRoot.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Green); });
        }

        void BlueInvoked(IUICommand command)
        {
            this.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue);
        }

        private void ShareButton_Click(object sender, EventArgs e)
        {
            InTheHand.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            InTheHand.ApplicationModel.Search.SearchPane.GetForCurrentView().Show();
        }

        private void SettingsButton_Click(object sender, EventArgs e)
        {
            InTheHand.UI.ApplicationSettings.SettingsPane.Show();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
}